<?php

namespace App\Console\Commands;

use App\Models\Staff;
use App\Models\StaffBonusPoolIncomeLog;
use App\Models\StaffTotalIncome;
use Illuminate\Console\Command;

class StaffIncome extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:staff-income';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        while (1){
//            $staff_income = StaffTotalIncome::whereId(1)->first();
            $staff_income = StaffTotalIncome::get();

            if (isset($staff_income[0]) && $staff_income[0]->useable_money && $staff_income[0]->useable_money >0){
                $staffs = Staff::get();
                foreach ($staffs as $staff){
                    $money = floor($staff_income[0]->useable_money * $staff->proportion);
                    try{
                        \DB::beginTransaction();
                        $staff->increment("useable_money", $money);
                        $staff->increment("total_money",$money);
                        // todo 员工 收益日志

                        $staff_bonus_pool_income_log  = new StaffBonusPoolIncomeLog();
                        $staff_bonus_pool_income_log->staff_id = $staff->id;
                        $staff_bonus_pool_income_log->money = $money;
                        $staff_bonus_pool_income_log->proportion = $staff->proportion;
                        $staff_bonus_pool_income_log->save();
                        \DB::commit();
                        $a = 1;
                    }catch (\Exception $exception){
                        \DB::rollBack();
                        \Log::error($exception);
                        $a = 0;

                    }

                }
                if ($a == 1){
                    $staff_income[0]->useable_money = 0;
                    $staff_income[0]->save();
                }
            }else{
                echo 'game over';
                sleep(10);
            }


        }


    }
}
